package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.AlertDataHandleDto;
import com.zzyl.dto.AlertDataPageQueryDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.AlertDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AlertDataServiceImpl implements AlertDataService {
    @Autowired
    AlertDataMapper mapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;

    @Override
    public PageResponse<AlertDataVo> pageQuery(AlertDataPageQueryDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        Page<AlertDataVo> dataVoPage = mapper.pageQuery(dto);
        return PageResponse.of(dataVoPage, AlertDataVo.class);
    }

    @Override
    public void handleAlertData(Long id, AlertDataHandleDto dto) {
        Boolean bool = redisTemplate.opsForValue().setIfAbsent("设备报警数据id:" + id, JSONUtil.toJsonStr(dto));
        if (Boolean.TRUE.equals(bool)) {
            AlertData alertData = BeanUtil.copyProperties(dto, AlertData.class);
            Long userId = UserThreadLocal.getUserId();
            List<User> users = userMapper.selectUserByIds(List.of(userId));
            alertData.setProcessorId(userId);
            alertData.setProductName(users.get(0).getRealName());
            mapper.handleAlertData(alertData);
        } else {
            AlertData alertData = mapper.selectById(id);
            log.info("处理人：{}", alertData.getProductName());
            throw new BaseException(BasicEnum.HAVE_ALREADY_DEALT_WITH_WARNING);
        }
    }
}
